﻿using System;
using MiHoMiao.DataBase;
using MiHoMiao.Mono.Singleton;
using TMPro;
using TodoList.Mono.TaskCreator;
using TodoList.Mono.TodoTask;
using TodoList.TodoTask;
using UnityEngine;
using UnityEngine.UI;

namespace TodoList.Mono.MainObject
{
    public partial class Main : MonoSingleton<Main>
    {
        public SqlAccess SqlAccess;
        
        [SerializeField] private Transform ItemContainer;
        [SerializeField] private TodoTaskItem ItemPrefab;
        [SerializeField] private TaskGenerator TaskGeneratorPrefab;
        [SerializeField] private Image DoneImage;
        [SerializeField] private TextMeshProUGUI TodayText;
        [SerializeField] private TextMeshProUGUI TimeText;
        public GameObject NewButton;

        private static readonly string[] m_Weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        protected override void OnAwake()
        {
            Application.logMessageReceived += HandleLog;
            SqlAccess = new SqlAccess(Application.persistentDataPath + "/TaskTodo.db");
            SqlAccess.CreateTable<TodoTaskTable>();
            TimeText.text = $"{DateTime.Now:yyyy年MM月dd日}, {m_Weekdays[(int)DateTime.Now.DayOfWeek]}";
            QueryAll();
            return;

            void HandleLog(string logString, string stackTrace, LogType type)
            {
                if (type != LogType.Error && type != LogType.Exception) return;
                TodayText.text += logString + "\n";
                TodayText.text += stackTrace + "\n\n";
            }
        }

        public static void QueryAll()
            => Instance.Refresh(
                $"select * from {nameof(TodoTaskTable)} where {nameof(TodoTaskTable.IsDone)} = 0"
            );
        
        public void Refresh(string sql)
        {
            CloseAllPrefabs();
            OpenAllPrefabs(SqlAccess.Query<TodoTaskTable>(sql));
        }
        
    }
}